package com.medsoft.perfstat.service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.AbstractRefreshableApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cyl.kernel.BusinessException;
import com.cyl.kernel.util.Base64Util;
import com.medsoft.perfstat.as.MonitoredMySQLService;
import com.medsoft.perfstat.dao.MetadataDAO;
import com.medsoft.perfstat.pojo.Apps;

@Service
public class MetadataService {
	static final Logger logger = LoggerFactory.getLogger(MetadataService.class);
	@Autowired
	private MetadataDAO metadataDAO;

	@Autowired
	private MonitoredMySQLService monitoredMySQLService;
	
	@Autowired
	private PerfStatSrcService perfStatSrcService;

	public List<Apps> queryHosts() {
		return metadataDAO.queryApps("",0);
	}

	public boolean addApps(Apps apps, HttpServletRequest request) {
		try {
			Apps tmpApps = new Apps();
			tmpApps.setHostname(apps.getHostname());
			tmpApps.setSshPort(apps.getSshPort());
			tmpApps.setSshUsername(apps.getSshUsername());
			tmpApps.setSshPassword(Base64Util.getBase64(apps.getSshPassword()));
			perfStatSrcService.getOSUptime(tmpApps);
		} catch (BusinessException e) {
			return false;
		}
		try {
			WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext(),"org.springframework.web.servlet.FrameworkServlet.CONTEXT.springMVC");
			if (context.getParent() != null) {
				metadataDAO.addApps(apps);
				((AbstractRefreshableApplicationContext) context.getParent()).refresh();
				((AbstractRefreshableApplicationContext) context).refresh();
				//重新加载并打开数据源
				metadataDAO.queryAppname();
			}
		} catch (Exception e) {
			logger.error("增加被监控MySQL发生异常：", e);
		}
		return true;
	}
}
